<template>
  <div class="repair-statistics">
    <el-card>
      <el-form inline>
        <el-form-item label="关键词">
          <el-input v-model="filters.keyword" placeholder="输入关键词" clearable />
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="filters.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchRepairs">搜索</el-button>
        </el-form-item>
      </el-form>

      <div class="charts-container">
        <div ref="lineChart" class="chart full-width"></div>
        <div ref="pieChart" class="chart"></div>
        <div ref="barChart" class="chart"></div>
      </div>
    </el-card>
  </div>
</template>

<script>
import Vue from 'vue';
import * as echarts from 'echarts';
import { parseTime } from '@/utils';

export default Vue.extend({
  data() {
    return {
      repairList: [],
      filters: {
        keyword: '',
        dateRange: []
      },
      chartRefs: {
        lineChart: null,
        pieChart: null,
        barChart: null
      },
      statusOptions: ['待处理', '处理中', '已完成', '已关闭'],
      mockDescriptions: [
        '水管漏水', '电梯故障', '门禁损坏', 
        '电路故障', '空调不制冷', '墙面脱落',
        '楼道灯损坏', '下水道堵塞', '消防设施故障',
        '停车场道闸故障'
      ]
    };
  },
  mounted() {
    this.fetchRepairs();
  },
  methods: {
    generateMockData() {
      const data = [];
      const startDate = new Date(2023, 11, 1); // 2023-12-01
      const endDate = new Date(2024, 2, 31);   // 2024-03-31
      
      for (let i = 0; i < 100; i++) {
        const randomDate = new Date(
          startDate.getTime() + Math.random() * (endDate.getTime() - startDate.getTime())
        );
        
        data.push({
          id: i + 1,
          description: this.mockDescriptions[Math.floor(Math.random() * this.mockDescriptions.length)],
          date: parseTime(randomDate, '{y}-{m}-{d}'),
          status: this.statusOptions[Math.floor(Math.random() * this.statusOptions.length)]
        });
      }
      return data;
    },

    filterData(data) {
      const [start, end] = this.filters.dateRange || [];
      return data.filter(item => {
        const inDateRange = !start || !end || 
          (item.date >= start && item.date <= end);
        const keywordMatch = !this.filters.keyword ||
          item.description.includes(this.filters.keyword);
        return inDateRange && keywordMatch;
      });
    },

    fetchRepairs() {
      const mockData = this.generateMockData();
      this.repairList = this.filterData(mockData);
      this.$nextTick(() => this.updateCharts());
    },

    updateCharts() {
      this.initLineChart();
      this.initPieChart();
      this.initBarChart();
    },

    initLineChart() {
      const chartData = this.repairList.reduce((acc, item) => {
        acc[item.date] = (acc[item.date] || 0) + 1;
        return acc;
      }, {});

      const dates = Object.keys(chartData).sort();
      const values = dates.map(date => chartData[date]);

      this.initChart('lineChart', {
        title: { text: '每日报修趋势' },
        xAxis: { type: 'category', data: dates },
        yAxis: { type: 'value' },
        series: [{
          type: 'line',
          data: values,
          smooth: true,
          areaStyle: {}
        }]
      });
    },

    initPieChart() {
      const statusData = this.repairList.reduce((acc, item) => {
        acc[item.status] = (acc[item.status] || 0) + 1;
        return acc;
      }, {});

      this.initChart('pieChart', {
        title: { text: '状态分布' },
        tooltip: { trigger: 'item' },
        series: [{
          type: 'pie',
          radius: '55%',
          data: Object.entries(statusData).map(([name, value]) => ({
            name,
            value
          }))
        }]
      });
    },

    initBarChart() {
      const statusData = this.repairList.reduce((acc, item) => {
        acc[item.status] = (acc[item.status] || 0) + 1;
        return acc;
      }, {});

      this.initChart('barChart', {
        title: { text: '状态统计' },
        xAxis: { type: 'category', data: Object.keys(statusData) },
        yAxis: { type: 'value' },
        series: [{
          type: 'bar',
          data: Object.values(statusData),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 1, color: '#188df0' }
            ])
          }
        }]
      });
    },

    initChart(refName, option) {
      if (!this.$refs[refName]) return;
      const chart = this.chartRefs[refName] || echarts.init(this.$refs[refName]);
      chart.setOption(option);
      this.chartRefs[refName] = chart;
      
      // 窗口 resize 时自动调整图表
      window.addEventListener('resize', () => chart.resize());
    }
  }
});
</script>

<style lang="scss" scoped>
.repair-statistics {
  padding: 20px;

  .charts-container {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    margin-top: 20px;

    .chart {
      height: 400px;
      background: #fff;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);

      &.full-width {
        width: 100%;
      }

      &:not(.full-width) {
        flex: 1;
        min-width: 45%;
      }
    }
  }

  ::v-deep .el-card__body {
    padding: 20px;
  }
}
</style>